<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<style type="text/css">
		#test{
			width: 450px;
		}
	</style>

	<body>
		<button type="button" id="button1" onclick="document.getElementById('test').focus(); insertHtmlAtCaret(1);">插入上标</button>
		<button type="button" id="button2" onclick="document.getElementById('test').focus(); insertHtmlAtCaret(2);">插入下标</button>
		<div contentEditable="true" style="height:50px; border:2px solid red;" id="test"> </div>
	</body>
	<script type="text/javascript">
		function insertHtmlAtCaret(type) {
			var html;
			var a = document.getElementById('button1').innerHTML;
			var b = document.getElementById('button2').innerHTML;
			if (type == 1) {
				if (document.getElementById('button1').innerHTML == "插入上标") {
					document.getElementById('button1').innerHTML = "插入上标1"
					html = "<sup>1</sup>";
				} else {
					document.getElementById('button1').innerHTML = "插入上标"
					html = "2";
				}
			} else {
				if (document.getElementById('button2').innerHTML == "插入下标") {
					document.getElementById('button2').innerHTML = "插入下标2"
					html = "<sub>1</sub>";
				} else {
					document.getElementById('button2').innerHTML = "插入下标1"
					html = "2";
				}
			}
			var sel, range;
			if(window.getSelection) {
				// IE9 and non-IE
				sel = window.getSelection();
				if(sel.getRangeAt && sel.rangeCount) {
					range = sel.getRangeAt(0);
					range.deleteContents();
					// Range.createContextualFragment() would be useful here but is
					// non-standard and not supported in all browsers (IE9, for one)
					var el = document.createElement("div");
					el.innerHTML = html;
					var frag = document.createDocumentFragment(),
						node, lastNode;
					console.log(el);
					console.log(node);
					console.log(el.firstChild);
					while((node = el.firstChild)) {
						lastNode = frag.appendChild(node);
					}
					console.log(frag);
					range.insertNode(frag);
					console.log(range);
					// Preserve the selection
					console.log(lastNode);
					if(lastNode) {
						range = range.cloneRange();
						range.setStartAfter(lastNode);
						range.collapse(true);
						sel.removeAllRanges();
						sel.addRange(range);
					}
					console.log(range);
				}
			} else if(document.selection && document.selection.type != "Control") {
				// IE < 9
				document.selection.createRange().pasteHTML(html);
			}
		}
	</script>

</html>